package org.vectrics.skill.struts;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Category;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.skill.Skill;
import org.vectrics.skill.SkillException;
import org.vectrics.skill.SkillRating;
import org.vectrics.skill.SkillRatingSet;
import org.vectrics.skill.SkillSetUtil;


abstract public class ShowSkillSectionsTagAbstract extends TagSupport {

	private static final long serialVersionUID = -8485610648861255440L;

	private static Category log = Category.getInstance(ShowSkillSectionsTagAbstract.class);
    public static String ENTRY_TYPE_PARAM = "entry_type";
    public static String EDIT_PARAM = "edit_skills";
    public static String JOB_PARAM = "job";
    private boolean editMode = false;
    private String entryTypeParam = "";
    
    

    public ShowSkillSectionsTagAbstract() {
    	//
    }

    abstract protected SkillRatingSet getSkillRatingSet() throws SkillException;
    abstract protected boolean getShowSkillDetails();
    abstract protected String getSectionEditLinkHtml(Skill skill);
    	
   	public int doStartTag() throws JspException  {
   		log.debug("doStartTag() called");
   		HttpServletRequest request = (HttpServletRequest)super.pageContext.getRequest();
   		String contextPath = request.getContextPath();
   		
   		Skill rootSkill = null;
		rootSkill = RecruitServiceLocator.getSkillProvider().getRootSkill();
   		
   		
        String entryTypeParam = request.getParameter(ENTRY_TYPE_PARAM);
        String editParam = request.getParameter(EDIT_PARAM);
        if ((editParam != null) && (editParam.startsWith("true"))) {
            editMode = true;
        }

        SkillRatingSet owner = null;        
        String jobId = request.getParameter(JOB_PARAM);
        
        try {
        	owner = getSkillRatingSet();
        }
        catch (SkillException se) {
        	log.error("Exception finding the skillRatingSet while displaying skill summary", se);
        	throw new JspException("Exception finding the skillRatingSet while displaying skill summary", se);
        }
            
        
        log.debug("doRender() - geting content for skills table.");
        
        StringBuffer html = new StringBuffer();
        html.append("<br>");
        html.append(getSkillTable(rootSkill, owner, request));
        
        JspWriter writer = pageContext.getOut();
        try {
        	writer.print(html.toString());
        }
        catch (IOException ex) {
        	throw new JspException("IOException attempting to write tag to output. " + ex.getMessage());
        }
        return(EVAL_PAGE);
        
   	}
    
    
    
    public Table getSkillTable(Skill rootSkill, SkillRatingSet owner, 
    			HttpServletRequest request) throws JspException   {        
        log.debug("Building skill summary table");
        Table table = new Table();

        table.setCellSpacing(8);
        table.setWidth("400");

        Row row1 = table.addRow();
        row1.setBgColor("#003040");
        
		

        try {
            SkillSetUtil util = new SkillSetUtil(owner, rootSkill);
            log.debug("getSkillTable(), clearing implied skills");
            util.clearImpliedParentSkills();
            log.debug("getSkillTable(), clearing unrated skills");
            util.clearUnrated();
            log.debug("getSkillTable(), showing skills");
            showSkills(request, table, rootSkill, owner, rootSkill, 0);

        }
        catch (Exception ex) {
            log.error("Exception displaying user skills.", ex);
            throw new JspException("Exception displaying user skills." +  ex.getMessage());
        }

        return(table);
    };


    void showSkills(HttpServletRequest request, Table mainTable, Skill rootSkill, SkillRatingSet owner, Skill parent, int indent) {
        if (log.isDebugEnabled())
            log.debug("showSkills()  parent: " + parent.getCode());
        Iterator iter = parent.getChildren().iterator();
        while (iter.hasNext()) {
            Skill childSkill = (Skill)iter.next();
            if (childSkill.getSection()) {
            	showSkillSection(request, mainTable, rootSkill, owner, childSkill, indent);
            }
//            SkillSetUtil util = new SkillSetUtil(owner, rootSkill);
//            if (util.getUserHasParentSkill(childSkill)) {
                showSkills(request, mainTable, rootSkill, owner, childSkill, indent + 1);
//            }
        }
        
    }
    
    void showSkillSection(HttpServletRequest request, Table mainTable, Skill rootSkill, SkillRatingSet owner, Skill skill, int indent) {
        if (log.isDebugEnabled())
            log.debug("showSkill() called.  Skill = " + skill.getCode());
        SkillRating rating = owner.findSkillRating(skill);
        log.debug("showSkill() - making row for skill");
        Row row = mainTable.addRow();
        Cell mainCell = row.addCell();
        

        Table sectionTable = new BorderTable();
        sectionTable.setWidth("100%");
        Row hdrRow = sectionTable.addRow();
        hdrRow.setDefaultBgImage(request.getContextPath() + "/site-graphics/tbl_hdr.gif");
        Cell hdrCell = hdrRow.addCell();
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", skill.getDescription()));
		
		
        mainCell.addElement(sectionTable);
        Row contentRow = sectionTable.addRow();
        Cell contentCell = contentRow.addCell();
        Table contentTable = new Table();
        contentTable.setWidth("100%");
        contentCell.addElement(contentTable);
        Row lowerRow = contentTable.addRow();

        Cell skillsCell = lowerRow.addCell();
        Cell linkCell = lowerRow.addCell();
        
        String buttonHtml = getSectionEditLinkHtml(skill);
        linkCell.setAlign("right");
        linkCell.addElement(buttonHtml);
        
        Table skillTable = new Table();
        skillTable.setWidth("100%");
        skillsCell.addElement(skillTable);
        
        Vector skillDescriptions = new Vector();
        getUserSkillDescriptions(skill, skillDescriptions, owner);
        Iterator descIter = skillDescriptions.iterator();
        if (descIter.hasNext()) {
	        while (descIter.hasNext()) {
		        Row skillRow = skillTable.addRow();
		        Cell skillCell = skillRow.addCell();
		        String description = (String)descIter.next();
		        skillCell.addElement(TextHelper.getFont("subFont", description));
	        }
        } else {
        	Row skillRow = skillTable.addRow();
        	Cell skillCell = skillRow.addCell();
        	skillCell.addElement(TextHelper.getFont("subFont", "<i>No Skills in This Section</i>"));
        	
        }
        log.debug("showSkill() - done.");
    }
   
    
    private void getUserSkillDescriptions(Skill skill, Collection skillDescriptions, SkillRatingSet owner) {
    	if ((skill.getNeedsRating()) && (owner.findSkillRating(skill) != null)) {
    		skillDescriptions.add(skill.getDescription());
    	}
    	Iterator iter = skill.getChildren().iterator();
    	while (iter.hasNext()) {
    		Skill childSkill = (Skill)iter.next();
    		if (childSkill.getSection() == false) {
    			getUserSkillDescriptions(childSkill, skillDescriptions, owner);
    		}
    		else {
    			log.debug("Child skill is a new section, don't place in the current section");
    		}
    	}
    }
    

}